#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import socket
import uuid
from typing import Tuple
from cryptography.fernet import Fernet
from logger import logger

def generate_node_id() -> str:
    """生成节点唯一标识"""
    return str(uuid.uuid4())

def generate_encryption_key() -> bytes:
    """生成加密密钥"""
    return Fernet.generate_key()

class Encryptor:
    def __init__(self, key: bytes):
        self.fernet = Fernet(key)
    
    def encrypt(self, data: bytes) -> bytes:
        """加密数据"""
        try:
            return self.fernet.encrypt(data)
        except Exception as e:
            logger.error(f'加密数据失败: {e}')
            return b''
    
    def decrypt(self, data: bytes) -> bytes:
        """解密数据"""
        try:
            return self.fernet.decrypt(data)
        except Exception as e:
            logger.error(f'解密数据失败: {e}')
            return b''

def get_local_ip() -> str:
    """获取本机IP地址"""
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('8.8.8.8', 80))
        ip = s.getsockname()[0]
        s.close()
        return ip
    except Exception as e:
        logger.error(f'获取本机IP失败: {e}')
        return '127.0.0.1'

def parse_address(address: str) -> Tuple[str, int]:
    """解析地址字符串为IP和端口"""
    try:
        host, port = address.split(':')
        return host, int(port)
    except Exception as e:
        logger.error(f'解析地址失败: {e}')
        return '', 0